/**
 * 类似流星雨小游戏
 *
 * @author li.youxi
 * @date 2017/05/25
 */

require('./index.scss');

var tpl = require('./index.html'),
	doc = document;

var TWEEN = require('libs/Tween.js'),
	sniff = require('libs/sniff.js');

window.rainFlag = true;

var classObj = {
		origin: ['rain-item', 'index']
	},
	dataObj = require('./data.js');

var rainObj = {

	//游戏窗口及游戏对象数据
	windowHeight: 0,
	windowWidth: 0,
	itemHeight: 0,
	itemNum: 37,
	c: 0,

	init: function(){
		//模板渲染
		doc.querySelector('#game_main').innerHTML = tpl;

		var item = doc.querySelector('.'+classObj.origin[0]);
		this.windowHeight = window.innerHeight;
		this.windowWidth = window.innerWidth;
		this.itemHeight = item&&item.getBoundingClientRect().height||200;

		//事件绑定
		this.eventBind();
	},

	eventBind: function(){
		var _this = this;

		doc.querySelector('.close-btn').addEventListener('click', function(){
			_this.stop();
		});

		//item事件监听
		doc.querySelector('.rain-wrapper').addEventListener('click', function(e){
			var className = e.target.className;

			if(className.indexOf(classObj.origin[0])!=-1) {
				
				if(className.indexOf('active')==-1) {
					e.target.className +=' active';
				}
			}
			
		});
	},

	createDOM: function(){
		var res = [],
			i = 0;

		for(; i<this.itemNum; i++) {
			res.push('<div class="rain-item index'+i+'"></div>');
		}

		document.querySelector('.rain-wrapper').innerHTML = res.join('');
	},

	//游戏开始
	start: function(){
		//计数器
		this.count = 0;

		this.createDOM();
		this.animate();
		this.loop();


		var _this = this;
		setTimeout(function(){
			_this.stop();
		}, 100000);
	},
	//结束游戏
	stop: function(){
		window.rainFlag = false;

		gameObj.setStatus('result');
	},

	loop: function(time){
		var _this = this;
		//游戏结束
		if(!window.rainFlag) return false;

        requestAnimationFrame( function(){
        	// if(_this.count<_this.itemNum) {
        	// 	_this.tweenCreate(_this.count);
        	// 	_this.count++;
        	// }
        	

        	rainObj.loop();
        });
        if(sniff.ios && sniff.osVersion<=8.3) {
          TWEEN.update(new Date().getTime());
        } else {
          TWEEN.update();
        }    
	},

	animate: function(){
		for(var i=0; i<this.itemNum; i++) {
			this.tweenCreate(i);
		}
		
	},

	tweenCreate: function(index){
		var _this = this,
			
			element = '.'+classObj.origin.join('.');

		this.tweenFactory(index, element+index, function(idx){
			_this.tweenCreate(idx);
		});
	},

	/**
	 * [tweenFactory 生成Tween对象]
	 * @param  {[type]}   index   [当前元素的编号 eg: index0,index1...]
	 * @param  {[type]}   element [当前元素的dom]
	 * @param  {Function} cb      [动画完成事件回调]
	 * @return {[type]}           [description]
	 */
	tweenFactory: function(index, element, cb){
		var _this = this;
		//运动时间
		var conf = dataObj.configFn(_this.windowWidth, _this.windowHeight, _this.itemHeight, _this.itemNum);
		//console.log(conf.delay);
		new TWEEN.Tween(conf.start)
            .to({
            	x: conf.end.x,
				y: conf.end.y
            }, conf.duration)
            //.repeat( 2 )
            //.yoyo(false)
            .delay( conf.delay )
            .easing( TWEEN.Easing.Quartic.Out )
            .onUpdate( function() {
                _this.updateElement(element, this);
            })
            .onComplete(function(){
            	if(cb) {
            		cb(index);
            	}

            	//恢复元素状态
            	if(doc.querySelector(element)) {
            		doc.querySelector(element).className = classObj.origin.join(' ')+index;
            	}

            	
            })
            .start();
	},

	updateElement: function(idStr, params){
	    var box = doc.querySelector(idStr);
	    if(!box) return;
	    var s = box.style;
	    var transform = 'rotate('+(params.rotate||0)+'deg) translateX(' + Math.round(params.x) + 'px) translateY(' +
	        Math.floor(params.y||0) + 'px) rotate('+(params.rotate||0)+'deg)';
	    s.webkitTransform = transform;
	    s.transform = transform;
    }

};

globalMessage.on('init.rain', function(){
	rainObj.init();	
});

module.exports = rainObj;